﻿using DirectShowLib;
using DirectShowLib.DES;
using mediaControl.Vo;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using Microsoft.WindowsAPICodePack.Shell;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;

namespace mediaControl.Utils
{
    public class WriteFileUtil
    {
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="content"></param>
        /// <param name="model"></param>
        public static void writeFile(string filePath, string content, string model)
        {
            StreamWriter sw = null;
            try
            {
                switch (model)
                {
                    case "1":
                        sw = new StreamWriter(filePath, true);//文件追加
                        break;
                    case "2":
                        sw = new StreamWriter(filePath);//文件重写
                        break;
                    default:
                        sw = new StreamWriter(filePath, true);//文件追加
                        break;
                }
                sw.WriteLine(content);

            }
            catch (Exception ex)
            {
                MessageBox.Show("写入流异常：" + ex.ToString());
                return;
            }
            finally
            {
                sw.Close();//确保最后总会关闭流
            }
        }
        public static String readFile(string filePath)
        {
            string content = "";
            try
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    content = reader.ReadToEnd();
                }


            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误：{ex.Message}");
            }
            return content;
        }

        public static void renameFile(string oldFile, string newFile)
        {
            try
            {
                File.Move(oldFile, newFile);
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine("The file does not exist.");
            }
            catch (IOException ex)
            {
                Console.WriteLine("The file could not be renamed.");
            }

        }

        public static void CopyFile(string sourceFile,string targetFile) {
            try
            {
                File.Copy(sourceFile, targetFile, true); // true表示如果目标文件存在则覆盖
                //MessageBox.Show("文件复制成功！");
            }
            catch (IOException ioEx)
            {
                //MessageBox.Show("文件复制失败: " + ioEx.Message);
            }
        }

        public static ObservableCollection<ScreenVo> getScreenItemList()
        {
            ObservableCollection<ScreenVo> screenVos = new ObservableCollection<ScreenVo>();
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "/Config/screenlist.info";
            if (File.Exists(filePath))
            {
                string content = WriteFileUtil.readFile(filePath);
                if (!String.IsNullOrEmpty(content))
                {
                    screenVos = JsonConvert.DeserializeObject<ObservableCollection<ScreenVo>>(content);
                }
            }
            return screenVos;
        }
        public static ObservableCollection<ProgramItem> getSourceList(string fullFilePath)
        {
            ObservableCollection<ProgramItem> sourceList = new ObservableCollection<ProgramItem>();
            
            if (File.Exists(fullFilePath))
            {
                string content = readFile(fullFilePath);
                if (!String.IsNullOrEmpty(content))
                {
                   
                    JObject programJson = JsonConvert.DeserializeObject<JObject>(content);
                    if (programJson.ContainsKey("sourceList"))
                    {
                        sourceList = JsonConvert.DeserializeObject<ObservableCollection<ProgramItem>>((String)programJson.GetValue("sourceList"));
                    }
                }
            }
            return sourceList;
        }

        public static int getMusicTimes(string filePath)
        {
            if (!File.Exists(filePath)) {
                MessageBox.Show("文件不存在！");
                return 0;
            }
            int duration = 0;    //时长(秒)
            var mediaDet = (IMediaDet)new MediaDet();
            DsError.ThrowExceptionForHR(mediaDet.put_Filename(filePath));// find the video stream in the fileint index;
            var type = Guid.Empty;
            for (int index = 0; index < 1000 && type != MediaType.Video; index++)
            {
                mediaDet.put_CurrentStream(index);
                mediaDet.get_StreamType(out type);
            }
            // retrieve some measurements from the video
            double frameRate;
            mediaDet.get_FrameRate(out frameRate);
            var mediaType = new AMMediaType();
            mediaDet.get_StreamMediaType(mediaType);
            var videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader));
            DsUtils.FreeAMMediaType(mediaType);
            double mediaLength;//这个是视频长度，单位秒
            mediaDet.get_StreamLength(out mediaLength);
            duration = (int)mediaLength;

            return duration ;

        }

        [DllImport("user32.dll")]
        private static extern IntPtr GetDesktopWindow();

        [DllImport("user32.dll")]
        private static extern IntPtr GetWindowDC(IntPtr hWnd);

        [DllImport("gdi32.dll")]
        private static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, CopyPixelOperation rop);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

        private const int SRCCOPY = 0x00CC0020;

      
        /// <summary>
        /// 显示屏幕
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static BitmapSource Capture()
        {
            var screenSize = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            using (var screenBmp = new Bitmap(screenSize.Width, screenSize.Height))
            {
                using (var graphics = Graphics.FromImage(screenBmp))
                {
                    graphics.CopyFromScreen(0, 0, 0, 0, screenSize.Size);
                }
                IntPtr hBitmap = screenBmp.GetHbitmap();
                try
                {
                    var src = Imaging.CreateBitmapSourceFromHBitmap(
                        hBitmap,
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());

                    return src;
                }
                finally { 
                
                  NativeMethods.DeleteObject(hBitmap); // 释放资源
                    
                }
            }
        }

        public static class NativeMethods
        {
            [System.Runtime.InteropServices.DllImport("gdi32.dll")]
            [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
            public static extern bool DeleteObject(IntPtr hObject);
        }
        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="originalImage"></param>
        /// <param name="quality"></param>
        /// <returns></returns>
        public static byte[] CompressImage(byte[] originalImage, double quality)
        {
            // 确保质量在0到1之间
            quality = Math.Max(0, Math.Min(1, quality));

            // 从原始图片字节流创建BitmapFrame
            var image = BitmapFrame.Create(new MemoryStream(originalImage));

            // 创建JpegBitmapEncoder并设置质量
            var encoder = new JpegBitmapEncoder();
            encoder.QualityLevel = (byte)(quality * 95); // JpegBitmapEncoder的质量在0-95之间
            encoder.Frames.Add(image);

            // 使用MemoryStream保存压缩后的图片
            using (var outputStream = new MemoryStream())
            {
                encoder.Save(outputStream);
                return outputStream.ToArray();
            }
        }
        /// <summary>
        /// 获取缩略图
        /// </summary>
        /// <param name="videoPath"></param>
        /// <returns></returns>
        public static BitmapSource GetThumbnailByPath(string videoPath)
        {
            try
            {
                ShellFile shellFile = ShellFile.FromFilePath(videoPath);
                Bitmap bitmap = shellFile.Thumbnail.ExtraLargeBitmap;


                if (null != bitmap)
                {
                    int thumbnailSize = 100; // 设置缩略图的大小
                    Bitmap thumbnail = new Bitmap(bitmap, thumbnailSize, thumbnailSize);
                    IntPtr hBitmap = thumbnail.GetHbitmap();
                    return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                }
            }
            catch (Exception e) {
                return null;
            }
            // 如果不需要缩放，直接返回原图
            return null;

        }

        public static BitmapImage GetFolderIcon()
        {
            BitmapImage bitmapImage = new BitmapImage(new Uri("../Resources/Icons/icon_folder1.png", UriKind.Relative));
            // 如果不需要缩放，直接返回原图
            return bitmapImage;

        }
        private static bool IsImageFile(string filePath)
        {
            try
            {
                using (var image = new Bitmap(filePath))
                    return true;
            }
            catch (Exception ex) when (ex is ArgumentNullException || ex is NotSupportedException)
            {
                return false;
            }
        }
        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public static List<string> getImageList(string folderPath)
        {

            List<String> imageList = new List<string>();
            try
            {
                // 获取文件夹中所有文件的列表
                string[] files = Directory.GetFiles(folderPath);

                foreach (string file in files)
                {
                    if (IsImageFile(file))
                    {
                        imageList.Add(file);
                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Error reading folder content: " + ex.Message);
            }
            return imageList;
        }

        public static void SaveOpenList(string filePath) {
            string filePath1 = AppDomain.CurrentDomain.BaseDirectory + "/Config/historyList.info";
            ObservableCollection<string> list = new ObservableCollection<string>();
            if (File.Exists(filePath1))
            {

                string content = WriteFileUtil.readFile(filePath1);
                if (!String.IsNullOrEmpty(content))
                {
                    list = JsonConvert.DeserializeObject<ObservableCollection<string>>(content);
                }
            }
            if (list.Contains(filePath)) {
                return;
            }
            list.Add(filePath);
            writeFile(filePath1, JsonConvert.SerializeObject(list), "2");
        }

        public static ObservableCollection<string> GetHistoryList() {
            string filePath1 = AppDomain.CurrentDomain.BaseDirectory + "/Config/historyList.info";
            ObservableCollection<string> list = new ObservableCollection<string>();
            if (File.Exists(filePath1))
            {

                string content = WriteFileUtil.readFile(filePath1);
                if (!String.IsNullOrEmpty(content))
                {
                    list = JsonConvert.DeserializeObject<ObservableCollection<string>>(content);
                }
            }
            return list;
        }
    }
}
